#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>

#define BUFFER_SIZE 4096 /* 读缓冲区大小*/

/* 主状态机的两种可能状态，分析请求行，分析头部字段*/
enum CHECK_STATE
{
    CHECK_STATE_REQUESTLINE,
    CHECK_STATE_HEADER
};

enum LINE_STATUES
{
    LINE_OK = 0,
    LINE_BAD,
    LINE_OPEN
};

enum HTTP_CODE
{
    NO_REQUEST,
    GET_REQUEST,
    BAD_REQUEST,
    FORBIDDEN_REQUEST,
    INTERNAL_ERROR,
    CLOSED_CONNECTION
};

/* 为了简化问题，我们没有给客户端发送一个完整的http应答报文，而只是根据服务器的处理结果发送如下成功或失败的信息 */
static const char *szret[] = {"I get a correct result\n", "Something wrong\n"};

LINE_STATUES parseLine(char *buffer, int &checked_index, int &read_index)
{
    char temp;
    /* checked_index 指向buffer（应用程序读缓冲区）中当前正在分析的字节，read_index 指向buffer中客户端数据尾部的下一个字节，buffer中的[0,checked_index] 字节都已分析完毕，第[checked_index，read_index-1] 字节由下面循环挨个分析*/
    for (; checked_index < read_index; ++checked_index)
    {
        temp = buffer[checked_index];
        /* 如果当前字节时'\r' 回车符，则说明可能读取到一个完整的行*/
        if (temp == '\r')
        {
            /* \r 为当前buffer中最后一个字符时*/
            if ((checked_index + 1) == read_index)
            {
                return LINE_OPEN;
            }
            else if (buffer[checked_index + 1] == '\n')
            {
                buffer[checked_index++] = '\0';
                buffer[checked_index++] = '\0';
                return LINE_OK;
            }

            return LINE_BAD;
        }
        else if (temp == '\n')
        {
            // 前后已经判断过了
            //  if ((checked_index > 1) && buffer[checked_index - 1] == '\r')
            //  {
            //      buffer[checked_index++] = '\0';
            //      buffer[checked_index++] = '\0';
            //      return LINE_OK;
            //  }
            return LINE_BAD;
        }
    }

    return LINE_OPEN;
}

HTTP_CODE parse_requestline(char *temp, CHECK_STATE &checkstate)
{
    char *url = strpbrk(temp, " \t");
    /*如果请求行中没有空白字符或"\t" 字符，则HTTP请求必有问题"*/
    if (!url)
    {
        return BAD_REQUEST;
    }
    *url++ = '\0';

    char *method = temp;
    if (strcasecmp(method, "GET") == 0) /* 仅支持GET方法*/
    {
        printf("The request method is GET\n");
    }
    else
    {
        return BAD_REQUEST;
    }

    url += strspn(url, " \t");
    char *version = strpbrk(url, " \t");
    if (!version)
    {
        return BAD_REQUEST;
    }

    *version++ = '\0';
    version += strspn(version," \t");
    /* 仅支持HTTP/1.1*/
    if(strcasecmp(version,"HTTP/1.1")!=0)
    {
        return BAD_REQUEST;
    }

    
}